package com.ai.interceptor;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.ai.common.model.CtxSessionBag;
import com.ai.service.reviewed.service.IDlxxService;

/**
 * 登录拦截器<br>
 * 
 */
public class CheckLoginInterceptor extends HandlerInterceptorAdapter {
    @Value("${mainDomain}")
    private String mainDomain;
    @Resource(name = "idlxxService")
	private IDlxxService idlxxService;

    protected final Log log = LogFactory.getLog(getClass());

    /**
     * 
     * Method Name : preHandle<br>
     * 
     * Description : 登录拦截器
     * 
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     * @since
     *
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    	
    	Object yhid =request.getSession().getAttribute("yhid");
		Object token =request.getSession().getAttribute("token");
		String sessionUrl = request.getServletPath();
		if (yhid!=null&&token!=null) {
			//判断用户是否合法
			int isUser = idlxxService.isUserMarch(yhid.toString(), token.toString());
			if(isUser==1)
			{
				Map<String,String[]> pramMap = request.getParameterMap();
				String[] paramvaluearr = pramMap.get("hzdh");
				request.getSession().setAttribute("url", sessionUrl);
				if (paramvaluearr!=null) {
					request.getSession().setAttribute("ymid", paramvaluearr[0]);
				}
				response.sendRedirect(mainDomain+"/login/loginindex.action");
	            return false;
			}
		}
		else {
			Map<String,String[]> pramMap = request.getParameterMap();
			String[] paramvaluearr = pramMap.get("hzdh");
			request.getSession().setAttribute("url", sessionUrl);
			if (paramvaluearr!=null) {
				request.getSession().setAttribute("ymid", paramvaluearr[0]);
			}	
			response.sendRedirect(mainDomain+"/login/loginindex.action");
            return false;
		}
        
		return true;
    }

    /**
     * 后处理（调用了Service并返回ModelAndView，但未进行页面渲染）
     */
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 返回处理（已经渲染了页面）
     */
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        /**
         * 清除线程
         */
        CtxSessionBag.clear();
    }
}
